<template>
  <div class="device-map-container">
    <div id="device-map" :style="{ width: width, height: height }"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  name: 'DeviceMap',
  props: {
    // 设备列表
    devices: {
      type: Array,
      default: () => []
    },
    // 地图宽度
    width: {
      type: String,
      default: '100%'
    },
    // 地图高度
    height: {
      type: String,
      default: '400px'
    },
    // 是否显示单个设备（设备详情页面使用）
    singleDevice: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      map: null,
      markers: []
    }
  },
  mounted() {
    this.initMap()
  },
  watch: {
    devices: {
      handler(newDevices) {
        if (this.map && newDevices.length > 0) {
          this.updateMarkers()
        }
      },
      deep: true
    },
    singleDevice: {
      handler(newDevice) {
        if (this.map && newDevice) {
          this.showSingleDevice()
        }
      },
      deep: true
    }
  },
  methods: {
    // 初始化地图
    async initMap() {
      try {
        const AMap = await AMapLoader.load({
          key: '0cdc91f4237103ce2af02a8dc38bb797',
          version: '2.0',
          plugins: ['AMap.Marker', 'AMap.InfoWindow']
        })
        
        this.map = new AMap.Map('device-map', {
          zoom: 10,
          center: [116.397428, 39.90923], // 默认中心点（北京）
          mapStyle: 'amap://styles/normal'
        })
        
        // 如果有单个设备，显示单个设备
        if (this.singleDevice) {
          this.showSingleDevice()
        } else if (this.devices.length > 0) {
          // 如果有设备列表，显示所有设备
          this.updateMarkers()
        }
      } catch (error) {
        console.error('地图初始化失败:', error)
        this.$message.error('地图加载失败，请检查网络连接')
      }
    },
    
    // 显示单个设备
    showSingleDevice() {
      if (!this.singleDevice || !this.singleDevice.longitude || !this.singleDevice.latitude) {
        this.$message.warning('设备位置信息不完整')
        return
      }
      
      // 清除现有标记
      this.clearMarkers()
      
      const position = [this.singleDevice.longitude, this.singleDevice.latitude]
      
      // 创建标记
      const marker = new AMap.Marker({
        position: position,
        title: this.singleDevice.nodeName || '设备位置',
        icon: this.getDeviceIcon(this.singleDevice)
      })
      
      // 创建信息窗口
      const infoWindow = new AMap.InfoWindow({
        content: this.createInfoWindowContent(this.singleDevice),
        offset: new AMap.Pixel(0, -30)
      })
      
      // 点击标记显示信息窗口
      marker.on('click', () => {
        infoWindow.open(this.map, position)
      })
      
      this.map.add(marker)
      this.markers.push(marker)
      
      // 设置地图中心和缩放级别
      this.map.setCenter(position)
      this.map.setZoom(15)
    },
    
    // 更新多个设备标记
    updateMarkers() {
      // 清除现有标记
      this.clearMarkers()
      
      const validDevices = this.devices.filter(device => 
        device.longitude && device.latitude
      )
      
      if (validDevices.length === 0) {
        this.$message.warning('没有有效的设备位置信息')
        return
      }
      
      const positions = []
      
      validDevices.forEach(device => {
        const position = [device.longitude, device.latitude]
        positions.push(position)
        
        // 创建标记
        const marker = new AMap.Marker({
          position: position,
          title: device.nodeName || '设备',
          icon: this.getDeviceIcon(device)
        })
        
        // 创建信息窗口
        const infoWindow = new AMap.InfoWindow({
          content: this.createInfoWindowContent(device),
          offset: new AMap.Pixel(0, -30)
        })
        
        // 点击标记显示信息窗口
        marker.on('click', () => {
          infoWindow.open(this.map, position)
        })
        
        this.map.add(marker)
        this.markers.push(marker)
      })
      
      // 自适应显示所有标记
      if (positions.length > 1) {
        this.map.setFitView(this.markers)
      } else {
        this.map.setCenter(positions[0])
        this.map.setZoom(15)
      }
    },
    
    // 获取设备图标
    getDeviceIcon(device) {
      // 根据设备连接状态返回不同颜色的图标
      const color = device.connectStatus ? '#52c41a' : '#ff4d4f'
      return `data:image/svg+xml;base64,${btoa(`
        <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
          <circle cx="16" cy="16" r="12" fill="${color}" stroke="#fff" stroke-width="2"/>
          <circle cx="16" cy="16" r="6" fill="#fff"/>
        </svg>
      `)}`
    },
    
    // 创建信息窗口内容
    createInfoWindowContent(device) {
      return `
        <div style="padding: 10px; min-width: 200px;">
          <h4 style="margin: 0 0 8px 0; color: #333;">${device.nodeName || '未命名设备'}</h4>
          <p style="margin: 4px 0; color: #666;"><strong>传感器ID:</strong> ${device.sensorId || 'N/A'}</p>
          <p style="margin: 4px 0; color: #666;"><strong>设备型号:</strong> ${device.model || 'N/A'}</p>
          <p style="margin: 4px 0; color: #666;"><strong>位置:</strong> ${device.fullName || 'N/A'}</p>
          <p style="margin: 4px 0; color: #666;"><strong>连接状态:</strong> 
            <span style="color: ${device.connectStatus ? '#52c41a' : '#ff4d4f'}">
              ${device.connectStatus ? '已连接' : '已断开'}
            </span>
          </p>
          <p style="margin: 4px 0; color: #666;"><strong>坐标:</strong> ${device.longitude}, ${device.latitude}</p>
        </div>
      `
    },
    
    // 清除所有标记
    clearMarkers() {
      if (this.markers.length > 0) {
        this.map.remove(this.markers)
        this.markers = []
      }
    }
  },
  
  beforeDestroy() {
    if (this.map) {
      this.map.destroy()
    }
  }
}
</script>

<style scoped>
.device-map-container {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

#device-map {
  width: 100%;
  height: 100%;
}
</style>